using B.S.ReportEvent.ErrorCode.ErrorCodes;
using Microsoft.AspNetCore.Mvc.Filters;

namespace B.S.ReportEvent.Api.Utils;

/// <summary>
/// 全局异常过滤器
/// </summary>
public class GlobalExceptionFilter : IAsyncExceptionFilter
{
    /// <summary>
    /// 日志
    /// </summary>
    private readonly ILogger<GlobalExceptionFilter> _logger;
    
    /// <summary>
    /// 构造函数注入
    /// </summary>
    /// <param name="logger"></param>
    public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
    {
        _logger = logger;
    }
    
    /// <summary>
    /// 异常处理
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public Task OnExceptionAsync(ExceptionContext context)
    {
        //写异常日志
        _logger.LogError("【全局异常过滤器】：" + context.Exception.Message);
        //异常已经处理
        context.ExceptionHandled = true;
        
        //返回500错误
        context.Result = new Microsoft.AspNetCore.Mvc.ObjectResult(new
        {
            code = (int)StatusCodeEnum.Exception,
            msg = context.Exception.Message,
            isSuc = false,
        })
        {
            StatusCode = StatusCodes.Status500InternalServerError
        };
        
        return Task.CompletedTask;
    }
}